package com.itheima.service.impl;

import com.itheima.dao.QuestionItemDao;
import com.itheima.domain.QuestionItem;
import com.itheima.service.QuestionItemService;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

public class QuestionItemServiceImpl implements QuestionItemService {

    @Override
    public void save(QuestionItem questionItem) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao questionItemDao = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);
            String id = UUID.randomUUID().toString();
            questionItem.setId(id);
            questionItemDao.save(questionItem);
            MybatisUtil.commit(sqlSession);
        } finally {
            MybatisUtil.close(sqlSession);
        }

    }

    @Override
    public QuestionItem findById(String id) {
        SqlSession sqlSession = null;
        QuestionItem questionItem= null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao questionItemDao = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);
            questionItem = questionItemDao.findById(id);
            MybatisUtil.commit(sqlSession);
        } finally {
            MybatisUtil.close(sqlSession);
        }
        return questionItem;
    }

    @Override
    public void update(QuestionItem questionItem) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao questionItemDao = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);

            questionItemDao.update(questionItem);
            MybatisUtil.commit(sqlSession);
        } finally {
            MybatisUtil.close(sqlSession);
        }

    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao questionItemDao = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);
            questionItemDao.delete(id);
            MybatisUtil.commit(sqlSession);
        } finally {
            MybatisUtil.close(sqlSession);
        }
    }

    @Override
    public List<QuestionItem> findAll(String questionId) {
        SqlSession sqlSession = null;
        List<QuestionItem> list = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao questionItemDao = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);
            list=questionItemDao.findAll(questionId);

        } finally {
            MybatisUtil.close(sqlSession);
        }

        return list;
    }
}
